<template>
  <el-card class="card">
    <el-alert title="添加教师信息" type="info" show-icon center :closable="false"/>

    <el-steps :active="(stepIndex - '0') === 3 ? 4 : (stepIndex - '0')" finish-status="success">
      <el-step title="基本信息"/>
      <el-step title="教师信息"/>
      <el-step title="教师简介"/>
      <el-step title="添加结果"/>
    </el-steps>

    <el-form ref="addTeacherFormRef"
             :model="addTeacherForm"
             :rules="addTeacherFormRules"
             status-icon
    >
      <el-tabs
        tab-position="left" class="tabs" v-model="stepIndex " @tab-click="tabChanged" :before-leave="validFieldFilter">
        <el-tab-pane label="基本信息" name="0">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工号" prop="userName">
                <el-input v-model="addTeacherForm.userName"/>
              </el-form-item>
              <el-form-item label="姓名" prop="nickName">
                <el-input v-model="addTeacherForm.nickName"/>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="addTeacherForm.sex">
                  <el-radio label="0" size="large">男</el-radio>
                  <el-radio label="1" size="large">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addTeacherForm.email" placeholder="请输入邮箱" maxlength="50"  label="top"/>
              </el-form-item>

            </el-col>
          </el-row>

          <el-button type="primary" @click="tabNextBase">下一步</el-button>
        </el-tab-pane>
        <el-tab-pane label="教师信息" name="1">

          <el-row :gutter="10">
            <el-col :span="5" >
              <el-form-item label="职称" prop="professional">
                <el-select style="width: 100%" v-model="addTeacherForm.professional" placeholder="请选择职称">
                  <el-option
                    v-for="dict in teacher_pro"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" >
              <el-form-item  label="职务" prop="post">
                <el-select style="width: 100%" v-model="addTeacherForm.post" placeholder="请选择职务" clearable>
                  <el-option
                    v-for="dict in teacher_post"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="10" >
              <el-form-item label="归属部门" prop="deptId">
                <treeselect style="width: 100%" v-model="addTeacherForm.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="10" >
              <el-form-item label="手机号码" prop="phonenumber" style="width: 100%">
                <el-input  v-model="addTeacherForm.phonenumber" placeholder="请输入手机号码" type="number" maxlength="11" />
              </el-form-item>
            </el-col>
          </el-row>
          <div>
            <el-button type="primary" @click="tabLastBase('0')">上一步</el-button>
            <el-button type="primary" @click="tabNextBaseB">下一步</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="教师简介" name="2">
          <el-row>
            <el-col :span="10">
              <el-form-item label="研究方向" prop="research">
                <el-input v-model="addTeacherForm.research"  placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <h4><strong style="color: #2b2f3a">简介</strong></h4>
            <editor v-model="addTeacherForm.brief" :min-height="192"/>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="addTeacherForm.remark" placeholder="请输入备注" />
          </el-form-item>
          <el-button type="primary" @click="tabLastBase('1')">上一步</el-button>
          <el-button type="primary" @click="addTeacher">下一步</el-button>

        </el-tab-pane>
        <el-tab-pane label="添加结果" name="3" :disabled="true">
          <el-result
            icon="success"
            title="添加成功"
            v-if="isStatus"
          >
            <template #extra>
              <el-button type="success" @click="$router.replace('/basic/teacher/##')">返回教师列表</el-button>
              <el-button type="primary" @click="nextAddTeacher()">继续添加教师</el-button>
            </template>
          </el-result>
          <el-result
            icon="error"
            title="添加失败"
            sub-title="请稍后再试或者联系系统管理员"
            v-if="!isStatus"
          >
            <template #extra>
              <el-button type="warning" @click="$router.replace('/basic/teacher')">返回教师列表</el-button>
            </template>
          </el-result>

        </el-tab-pane>
      </el-tabs>
    </el-form>

  </el-card>
</template>

<script>
import { getDicts } from '@/api/system/dict/data'
import { deptTreeSelect } from '@/api/system/user'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addTeacher, updateTeacher } from '@/api/contest/teacher'

export default {
  name: 'addTeacher',
  components: { Treeselect },


  // Huafv 凌陌笙 1295074635@qq.com
  data() {
    return {
      stepIndex: '0',
      // 表单参数
      addTeacherForm: {
        // 工号
        userName: null,
        // 姓名
        nickName: null,
        // 性别
        sex: '0',
        email: null,
        professional:null,
        post:null,
        phonenumber:undefined,
        status: '1',
        deptId: undefined,
        research:undefined,
        brief:undefined,
        remark:undefined,
      },
      sexDict: [],
      teacher_pro:[],
      teacher_post:[],
      deptOptions:[],
      isStatus: false,
      addTeacherFormRules: {
        userName: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 2, max: 20, message: '工号长度在2到20个字符之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 6, message: '姓名长度在2到6个字符之间', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        deptId: [
          { required: true, message: '您必须选择您所在的部门', trigger: 'blur' }
        ],
        professional:[
          { required: true, message: '您必须选择该项', trigger: 'blur' }
        ],
        post:[
          { required: true, message: '您必须选择该项', trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    // dicts: ['teacher_post', 'sys_user_sex', 'sys_normal_disable', 'teacher_pro'],

    getDict() {
      getDicts('sys_user_sex').then(resp => {
        this.sexDict = resp.data
      })
      getDicts('teacher_pro').then(resp => {
        this.teacher_pro = resp.data
      })
      getDicts('teacher_post').then(resp => {
        this.teacher_post = resp.data
      })
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    tabChanged(f) {
      // let tabIndex = f.index
      // this.stepIndex = tabIndex
    },
    tabNextBase() {
      let flag = true;
      const Field = ['userName', 'nickName', 'sex']
      for(let i = 0; i < Field.length; i++){
        flag = this.validField(Field[i])
        if(!flag) break;
      }
      if(flag){
        this.stepIndex = '1'
      }
    },
    validField(Field){
      let flag = null;
      this.$refs.addTeacherFormRef.validateField(Field, (errorMessage) => {
        let valid = errorMessage === '';
        if (!valid) {
          this.$message.error(errorMessage)
          flag = false
        }else{
          flag = true
        }
      })
      return flag
    },
    validFieldFilter(activeName, oldActiveName){
      if(oldActiveName === '0'){
        let flag = true;
        const Field = ['userName', 'nickName', 'sex']
        for(let i = 0; i < Field.length; i++){
          flag = this.validField(Field[i])
          if(!flag) break;
        }
        if(!flag){
          // this.$message.error("请必须完成当前信息填写，才可以进入下一步！")
        }else{
          this.stepIndex = activeName
        }
        return flag
      }
      if(oldActiveName === '1'){
        let flag = this.validField('deptId') && this.validField('post') && this.validField('professional')
        if(!flag){
          this.stepIndex = '1'
          return false
        }else{
          this.stepIndex = activeName
        }
      }

    },
    tabNextBaseB(){
      let flag = this.validField('deptId') && this.validField('post') && this.validField('professional')
      if(!flag){

      }else{
        this.stepIndex = '2'
      }
    },
    tabLastBase(index){
      this.stepIndex = index.toString()
    },

    addTeacher(){
      this.$refs["addTeacherFormRef"].validate(valid => {
        if (valid) {
            addTeacher(this.addTeacherForm).then(response => {
              console.log(response)
              if(response.code === 200){
                this.stepIndex = '3'
                this.$message.success("添加成功")
                this.isStatus = true
              }else{
                this.$message.error("添加失败")
              }
            });
        }
      });
    },
    nextAddTeacher(){
      this.reset()
      this.stepIndex = '0'
    },
    // 表单重置
    reset() {
      this.addTeacherForm =  {
        // 工号
        userName: null,
          // 姓名
          nickName: null,
          // 性别
          sex: undefined,
          email: null,
          professional:null,
          post:null,
          phonenumber:undefined,
          status: '1',
          deptId: undefined,
          research:undefined,
          brief:undefined,
          remark:undefined,
      }
    }

  },
  created() {
    this.getDict()
  },

}
</script>

<style scoped>
.card {
  margin: 10px;
}

.el-steps {

  margin-left: 20px;
  margin-right: 20px;
  margin-top: 10px;
}

.tabs {
  margin-top: 15px;
  height: 100%;
}

.el-tab-pane {
  padding-left: 10px;
}
</style>
